package ArrayList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: dch
 * @Date: 2020/6/8 21:57
 * @Description:  ArrayList随机访问和顺序访问效率对比
 */
public class ArrayListDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for(int i=0;i<100000;i++){
            list.add(i+"a");
        }
        //测试随机访问时间
        long startTime = System.currentTimeMillis();
        for(int i=0;i<list.size();i++){
            list.get(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("随机访问耗时："+(endTime-startTime));

        //测试顺序访问时间
        startTime = System.currentTimeMillis();
        //获取迭代器
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            iterator.next();
        }
        endTime = System.currentTimeMillis();
        System.out.println("顺序访问耗时："+(endTime-startTime));
    }
}
